package com.chz.SupermarketMS.controllers;

import com.chz.SupermarketMS.dao.InventoryRepository;
import com.chz.SupermarketMS.dto.CommodityInventories;
import com.chz.SupermarketMS.dto.CommodityPD;
import com.chz.SupermarketMS.entities.Commodity;
import com.chz.SupermarketMS.entities.Inventory;
import com.chz.SupermarketMS.service.CommodityService;
import com.chz.SupermarketMS.service.InventoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("inventories")
public class InventoryController {

    @Autowired
    InventoryService inventoryService;

    @Autowired
    CommodityService commodityService;

    @Autowired
    InventoryRepository inventoryRepository;

    @GetMapping
    public String displayInventory(Model model){
        List<Inventory> inventories = inventoryService.getAll();
        model.addAttribute("inventories",inventories);

        List<CommodityInventories> commodityInventories= inventoryRepository.commodityInventories();
        model.addAttribute("commodityInventories",commodityInventories);

        return "inventories/list-inventories";
    }

    @GetMapping("/new")
    public String displayInventoryForm(Model model){

        Inventory aInventory = new Inventory();
        List<Commodity> commodities = commodityService.getAll();
        model.addAttribute("allCommodities",commodities);
        model.addAttribute("inventory",aInventory);
        return "inventories/new-inventory";
    }

    @PostMapping("/save")
    public String createInventory(Model model,Inventory inventory){

        inventoryService.save(inventory);

        return "redirect:/inventories";
    }
    @GetMapping("/update")
    public String displayInventoryUpdateForm(@RequestParam("id") long theId, Model model) {
        Inventory theInventory = inventoryService.findByInventoryId(theId);
        model.addAttribute("inventory", theInventory);
        return "inventories/new-inventory";
    }


    @GetMapping("/delete")
    public String deleteInventory(@RequestParam("id")long theId, Model model) {
        Inventory theInventory = inventoryService.findByInventoryId(theId);
        inventoryService.delete(theInventory);
        return "redirect:/inventories";
    }






}
